import os
import json
import sys
import datetime
from copy import deepcopy
from feature_set.base_feature import BaseFeature, RequstData
from feature_set.sms.utils.data_process import time_trans


class SmsUnRuleV1(BaseFeature):

    def __init__(self):
        super().__init__()

        self.root_dir = self.get_root_dir(os.path.abspath("."))
        self.conf_dir = os.path.join(self.root_dir, "feature_conf")

        self.day_section = [(15, "d15"), (30, "m1"), (90, "m3"), (sys.maxsize, "all")]
        self.clean_sorted_sms_list = None
        
        self.country_info = None
        self.feature_dict = None
    
    def trans_str_to_time(self, str_time):
        return datetime.datetime.strptime(str_time, "%Y-%m-%d %H:%M:%S")
    
    def get_root_dir(self, path):
        path_list = path.split(os.path.sep)
        index = path_list.index("featurelib")
        return os.path.sep.join(path_list[: index + 1])
    
    
    def load_request(self, request_data):
        self.country_type = self.country_info["country_type"]
        apply_time = self.trans_str_to_time(request_data.apply_time)

        try:
            sms_list = []
            sms_data = request_data.data_sources["sms_data"]
            sms_list = json.loads(sms_data) if type(sms_data) == str else sms_data
        except:
            pass

        if len(sms_list) == 0 or type(sms_list) != list:
            assert (
                1 == 0
            ), "传入的sms_json无法解析或者解析后异常(不是list，或者为空list)"

        name_trans_hash = {
            "sender": self.phone_name,
            "content": self.body_name,
            "type": self.type_name,
            "sms_time": self.time_name,
        }

        trans_sms_list = []
        for sms in sms_list:
            if (
                self.phone_name not in sms
                or self.body_name not in sms
                or self.type_name not in sms
                or self.time_name not in sms
                or sms[self.time_name] == ""
            ):
                continue
            trans_sms = {}
            trans_sms["sender"] = sms[name_trans_hash["sender"]]
            trans_sms["sms_time"] = time_trans(sms[name_trans_hash["sms_time"]], self.country_type)
            trans_sms["type"] = int(sms[name_trans_hash["type"]])
            trans_sms["content"] = sms[name_trans_hash["content"]]
            trans_sms["diff_days"] = (
                apply_time.date() - trans_sms["sms_time"].date()
            ).days
            trans_sms_list.append(deepcopy(trans_sms))
        sorted_msg_list = sorted(
            trans_sms_list, key=lambda x: x["sms_time"], reverse=True
        )
        clean_sorted_sms_list = [
            trans_sms
            for trans_sms in sorted_msg_list
            if trans_sms["sms_time"].replace(tzinfo=None) < self.trans_str_to_time(request_data.apply_time)
            and trans_sms["type"] == 1
        ]
        return clean_sorted_sms_list
    
    def gen_features(self, data: RequstData):
        res_map = {}
        try:
            self.clean_sorted_sms_list = self.load_request(data)
        except AssertionError as e:
            for k, v in self.feature_dict.items():
                if v == 'str':
                    res_map[k] = ''
                else:
                    res_map[k] = -999
            return res_map
        res_map = self.get_cnt_feature(res_map)
        return res_map
    
    def _init_cnt_feature(self, res_map):
        res_map['sms_cnt'] = 0
        return res_map
    
    def get_cnt_feature(self, res_map):
        res_map = self._init_cnt_feature(res_map)
        res_map['sms_cnt'] = len(self.clean_sorted_sms_list)
        return res_map
